/** 定义新闻相关接口 */
const express = require("express");
const router = express.Router();
const Joi = require("joi");
const Response = require("../utils/Response");

// 引入mysql连接池
const pool = require("../utils/pool");

/** 添加类型（特色景点） */
router.post("/scenic-spot/class-add", (req, res) => {
  let { classname, cid, logo } = req.body;
  let schema = Joi.object({
    classname: Joi.string().required(),
    cid: Joi.number().required(),
    logo: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    console.log(error);
    res.send(Response.error(400, error));
    return;
  }
  let obj = { classname, cid, logo };
  const sql = "insert into sight_class set ?";
  pool.query(sql, obj, (error, result) => {
    if (error) {
      res.send(Response.error(500, error));
      throw error;
    }
    res.send(Response.ok());
  });
});

/** 添加类型（特色景点） */
router.post("/scenic-spot/class-update", (req, res) => {
  let { id, classname, cid, logo } = req.body;
  let schema = Joi.object({
    id: Joi.number().required(),
    classname: Joi.string().required(),
    cid: Joi.number().required(),
    logo: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    console.log(error);
    res.send(Response.error(400, error));
    return;
  }
  const sql = "update sight_class set classname=?,cid=? ,logo=? where id=?";
  pool.query(sql, [classname, cid, logo, id], (error, result) => {
    if (error) {
      res.send(Response.error(500, error));
      throw error;
    }
    res.send(Response.ok());
  });
});

/** 删除类型(特色景点) */
router.post("/scenic-spot/class-del", (req, res) => {
  let { id } = req.body;
  let schema = Joi.object({
    id: Joi.string().required(), // 必填
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    res.send(Response.error(400, error));
    return; // 结束
  }
  let sql = "delete from sight_class where id=?";
  pool.query(sql, [id], (error, result) => {
    if (error) {
      res.send(Response.error(500, error));
      throw error;
    }
    res.send(Response.ok());
  });
});
/** 查询所有类型 */
router.get("/scenic-spot/class", (req, res) => {
  let sql = "select * from sight_class";
  pool.query(sql, (error, result) => {
    if (error) {
      res.send(Response.error(500, error));
      throw error;
    }
    res.send(Response.ok(result));
  });
});

// 将router对象导出
module.exports = router;
